#!/bin/bash
checkMsg() {
awk -v rc=-1 -v m="$1" '$0~m {rc=0} ; {print}; END {exit rc}'
}
rm -rf /tmp/oom/
RC=0
httpPort=3755
export CA_CFG_PATH=/tmp/oom
export FABRIC_CA_CLIENT_HOME=/tmp/oom/admin
FABRIC_CA="$GOPATH/src/github.com/tjfoc/gmca"
SCRIPTDIR="$FABRIC_CA/scripts/fvt"
. $SCRIPTDIR/fabric-ca_utils
mkdir -p /FVT/crl/
cp $GOPATH/src/github.com/tjfoc/fabric-ca-gm/testdata/crl.pem /FVT/crl/crl.pem
$SCRIPTDIR/utils/pki -f newcert -p admin -t ec -l 256 -n '/C=US/CN=admin/ST=North Carolina/O=Hyperledger/OU=Fabric/CN=admin/' -x <<EOF
127.0.0.2

admin.fabric.raleigh.ibm.com
admin@fab-client.raleigh.ibm.com
Y
EOF

# Start the default server and check to see if CRL retrieval works if size limit is appropriate
# However, register will fail because we used a 'hacked' enrollment certificate
$SCRIPTDIR/fabric-ca_setup.sh -I -X -S -D
enroll
admin_keyfile="$(find /tmp/oom/admin/msp/keystore -type f)"
admin_certfile="/tmp/oom/admin/msp/signcerts/cert.pem"
hacker_admin_keyfile="/root/adminkey.pem"
hacker_admin_certfile="/root/admincert.pem"
cp $hacker_admin_keyfile $admin_keyfile
cp $hacker_admin_certfile $admin_certfile
cd /
python -m SimpleHTTPServer $httpPort &
pollServer httpserver 127.0.0.1 3755 10
register admin user1 2>&1 | checkMsg "Error: Error response from server was: Authorization failure"
test $? -ne 0 && ErrorMsg "Failed to return correct error"

# Lower the CRL size limit on server and check to see that server does not continue to proceed with retrieving CRL list
export FABRIC_CA_SERVER_CRLSIZELIMIT=10
cd $GOPATH/src/github.com/tjfoc/gmca
$SCRIPTDIR/fabric-ca_setup.sh -K
$SCRIPTDIR/fabric-ca_setup.sh -S -D -X > /tmp/log.txt 2>&1
enroll admin2 adminpw2
admin_keyfile="$(find /tmp/oom/admin/msp/keystore -type f)"
admin_certfile="/tmp/oom/admin/msp/signcerts/cert.pem"
hacker_admin_keyfile="/root/adminkey.pem"
hacker_admin_certfile="/root/admincert.pem"
cp $hacker_admin_keyfile $admin_keyfile
cp $hacker_admin_certfile $admin_certfile
register admin user2 client bank_a "" /tmp/oom/admin2 2>&1 | checkMsg "Error: Error response from server was: Authorization failure"
test $? -ne 0 && ErrorMsg "Failed to return correct error"
grep "failed to fetch CRL: Error reading CRL with max buffer size of 10: Size of requested data is too large" /tmp/log.txt &> /dev/null
if [ $? != 0 ]; then
   ErrorMsg "Client authentication failed for other reason than CRL size"
fi
CleanUp $RC
exit $RC
